package com.sinosoft.web.easyui.api;

import com.sinosoft.hydra.um.LoginUser;
import cn.com.sinux.spring.commons.PropertyCollection;
import com.sinosoft.hydra.um.condition.SearchOrganizationCondition;
import com.sinosoft.hydra.um.condition.SearchUserCondition;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.permission.SysOrganization;
import com.sinosoft.hydra.um.domain.permission.SysOrganizationUser;
import com.sinosoft.hydra.um.domain.permission.SysUserMember;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.SysOrganizationService;
import cn.com.sinux.spring.utils.BeanUtils;
import cn.com.sinux.spring.utils.PageUtils;
import cn.com.sinux.spring.json.JsonFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * <p/>
 * 课题组管理
 * <p/>
 *
 * @author oujianlin@sinosoft.co
 *         <p/>
 * @version v0.5
 */
@Controller
@RequestMapping(value = "/api/organization")
public class SysOrganizationApi {

    @Autowired
    private SysOrganizationService organizationService;

    /**
     * 课题组首页面，显示所有课题组
     *
     * @return
     */
    @RequestMapping(value = "gotoPage")
    @RequiresPermissions(value = "organization:data:list")
    public String gotoOrgPage() {
//        LoggerHelper.logInfo("查看了课题组列表信息");
        return "hydra_easyui/organization/index";
    }

    /**
     * 到课题组搜索页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "search")
    @RequiresPermissions(value = "organization:data:list")
    public String search(Model model) {
        return "hydra_easyui/organization/search";
    }

    /**
     * 查询课题组列表 JSON
     *
     * @param organization 查询条件
     * @param pageSize     每页大小
     * @param pageNumber   当前页起始的数据条数
     * @return
     */
    @RequestMapping(value = "/findAllByPage")
    @ResponseBody
    public Object findAllByPage(
            SearchOrganizationCondition organization,
            @RequestParam(value = "rows", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageNumber) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "id", "asc");
        organization.setLikeWords(true);
        Page<SysOrganization> page = organizationService.findAll(organization, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysOrganization.class, "id", "orgName", "orgJobs", "available", "depBelong"));
    }

    /**
     * 查询所有可用部门list
     *
     * @param searchOrganizationCondition 查询条件
     * @return
     */
    @RequestMapping(value = "/findAll")
    @ResponseBody
    public Object findAll(
            SearchOrganizationCondition searchOrganizationCondition) {
        searchOrganizationCondition.setAvailable(BaseConstant.INTEGER_TRUE);
        List<SysOrganization> list = organizationService.findAll(searchOrganizationCondition, null).getContent();
        return JsonFilter.doPropertyFilter(list, new PropertyCollection()
                .addProperties(SysOrganization.class, "id", "orgName", "orgJobs", "available"));
    }

    /**
     * 课题组新增保存
     *
     * @param organization ID不为null表示修改
     * @param organization 返回的页面地址(页面根目录：pages，如果页面在pages下面，直接传递文件名称)
     * @returnto
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @RequiresPermissions(value = "organization:data:add")
    @ResponseBody
    public Object addOrganizationForJson(SysOrganization organization) {
        SysOrganization org = organizationService.addOrganization(organization);
        LoggerHelper.logInfo("新增了课题组‘{}’", organization.getOrgName());
        return JsonFilter.doPropertyFilter(org, "id");
    }

    /**
     * 课题组编辑保存
     *
     * @param organization
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @RequiresPermissions(value = "organization:data:update")
    @ResponseBody
    public Object updateOrganizationForJson(SysOrganization organization) {
        SysOrganization db = organizationService.findOne(organization.getId());
        SysOrganization source = new SysOrganization();
        BeanUtils.copyProperties(db, source);
        SysOrganization target = organizationService.updateOrganization(organization);
        LoggerHelper.logInfo("修改了课题组‘{}’信息{}", db.getOrgName(), new LoggerHelper.PropertyMerge(source, target)
                        .addPropertyDes("orgName", "课题组名称")
        );
        return JsonFilter.doPropertyFilter(target, new PropertyCollection()
                .addProperties(SysOrganization.class, "id", "orgName"));
    }

    /**
     * 批量删除课题组
     *
     * @param searchOrganizationCondition
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @RequiresPermissions(value = "organization:data:delete")
    @ResponseBody
    public Object removeOrg(SearchOrganizationCondition searchOrganizationCondition) {
        List<SysOrganization> list = organizationService.deleteOrganizations(searchOrganizationCondition.getIds());
        LoggerHelper.logInfo("删除了课题组", new LoggerHelper.PropertyReader<SysOrganization>(list, "orgName"));
        return JsonFilter.doPropertyFilter(list, new PropertyCollection()
                .addProperties(SysOrganization.class, "id", "orgName"));
    }

    /**
     * 点击“新增课题组”
     *
     * @param model
     * @return
     */
    @RequestMapping("toAdd")
    @RequiresPermissions(value = "organization:data:add")
    public String toAdd(Model model, LoginUser loginUser) {
        return "hydra_easyui/organization/add";
    }

    /**
     * 点击“编辑”
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("toUpdate")
    @RequiresPermissions(value = "organization:data:update")
    public String toUpdate(
            @RequestParam(value = "id", required = true) String id,
            Model model, LoginUser loginUser) {
        SysOrganization organization = organizationService.findOne(id);
        model.addAttribute("organization", organization);
        return "hydra_easyui/organization/update";
    }

    /**
     * 点击"课题组成员管理"
     *
     * @param model
     * @return
     */
    @RequestMapping("toOrgManage")
    @RequiresPermissions(value = "organization:user:list")
    public String organizationManage(
            @RequestParam(value = "id", required = true) String orgId,
            Model model) {
        model.addAttribute("organization", organizationService.findOne(orgId));
        return "hydra_easyui/organization/orgManage";
    }


    /**
     * 查询课题组成员用户列表
     *
     * @param searchUserCondition 查询条件
     * @param pageSize            每页大小
     * @param pageNumber          当前页起始的数据条数
     * @return
     */
    @RequestMapping("findOrgUser")
    @ResponseBody
    public Object findOrgUser(SearchUserCondition searchUserCondition,
                              @RequestParam(value = "rows", defaultValue = "10", required = false) Integer pageSize,
                              @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageNumber) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "sysUserMember.id", "asc");
        Page<SysOrganizationUser> page = organizationService.findOrganizationUser(searchUserCondition, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysOrganizationUser.class, "id", "sysUserMember", "sysOrganization", "role")
                .addProperties(SysOrganization.class, "id", "orgName")
                .addProperties(SysUserMember.class, "id", "userName", "userNumber", "userHead", "orgsDescription",
                        "email", "mobile", "available", "alias"));
    }

    /**
     * 刷新课题组组长时返回orgUser的list
     *
     * @param searchUserCondition
     * @return
     */
    @RequestMapping("findLeader")
    @ResponseBody
    public Object findLeader(SearchUserCondition searchUserCondition) {
        List<SysOrganizationUser> list = organizationService.findOrganizationUser(searchUserCondition, null).getContent();
        return JsonFilter.doPropertyFilter(list, new PropertyCollection()
                .addProperties(SysOrganizationUser.class, "id", "sysUserMember")
                .addProperties(SysUserMember.class, "id", "userName", "userNumber"));
    }

    /**
     * 设置课题组组长
     *
     * @param id
     * @return
     */
    @RequestMapping("addLeader")
    @ResponseBody
    @RequiresPermissions("organization:leader:add")
    public Object addLeader(@RequestParam(value = "id", required = true) String id) {
        List<String> list = organizationService.leader(id, 1);
        final String userName = list.get(0);
        final String orgName = list.get(1);
        LoggerHelper.logInfo("将用户‘{}’设为课题组‘{}’组长", userName, orgName);
        return new HashMap<String, String>() {{
            put("userName", userName);
            put("orgName", orgName);
        }};
    }

    /**
     * 取消课题组组长
     *
     * @param id
     * @return
     */
    @RequestMapping("delLeader")
    @ResponseBody
    @RequiresPermissions("organization:leader:delete")
    public Object delLeader(@RequestParam(value = "id", required = true) String id) {
        List<String> list = organizationService.leader(id, 0);
        final String userName = list.get(0);
        final String orgName = list.get(1);
        LoggerHelper.logInfo("将用户‘{}’取消设为课题组‘{}’组长", userName, orgName);
        return new HashMap<String, String>() {{
            put("userName", userName);
            put("orgName", orgName);
        }};
    }

    /**
     * 到搜索课题组人员页面
     *
     * @param model
     * @return
     */
    @RequestMapping("toSearchOrgUser")
    public String searchDutyUser(Model model, @RequestParam(value = "orgId", required = true) String orgId) {
        model.addAttribute("org", organizationService.findOne(orgId));
        return "hydra_easyui/organization/searchOrgUser";
    }

    /**
     * 到添加课题组成员页面
     *
     * @param model
     * @return
     */
    @RequestMapping("toAddOrgUser")
    @RequiresPermissions(value = "organization:user:add")
    public String toAddOrgUser(Model model, @RequestParam(value = "orgId", required = true) String orgId) {
        model.addAttribute("orgId", orgId);
        return "hydra_easyui/organization/addOrgUser";
    }

    /**
     * 添加课题组成员时的用户列表
     *
     * @param searchUserCondition 查询条件
     * @param pageSize            每页大小
     * @param pageNumber          当前页起始的数据条数
     * @return
     */
    @RequestMapping("addOrgUserList")
    @ResponseBody
    public Object addOrgUserList(SearchUserCondition searchUserCondition,
                                 @RequestParam(value = "rows", defaultValue = "10", required = false) Integer pageSize,
                                 @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageNumber) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "id", "asc");
        Page<SysUserMember> page = organizationService.findOrgUsers(searchUserCondition, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysUserMember.class, "id", "userName", "userNumber", "orgsDescription", "alias", "available"));
    }

    /**
     * 添加课题组成员
     *
     * @return
     */
    @RequestMapping(value = "addOrgUsers", method = RequestMethod.POST)
    @RequiresPermissions(value = "organization:user:add")
    @ResponseBody
    public Object addOrgUsers(SearchOrganizationCondition condition) {
        final SysOrganization sysOrganization = organizationService.findOne(condition.getId());
        List<SysUserMember> userMembers = organizationService.addOrgUsers(condition.getId(), condition.getUserIds(), false);
        LoggerHelper.logInfo("小组‘{}’下新增了成员‘{}’", sysOrganization.getOrgName(), new LoggerHelper.PropertyReader<SysUserMember>(userMembers, "userName"));
        return new HashMap<String, String>() {{
            put("orgName", sysOrganization.getOrgName());
        }};
    }

    /**
     * 删除课题组成员
     *
     * @param condition
     * @return
     */
    @RequestMapping(value = "deleteOrgUsers", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = "organization:user:delete")
    public Object deleteOrgUsers(SearchOrganizationCondition condition) {
        final SysOrganization sysOrganization = organizationService.findOne(condition.getId());
        List<SysUserMember> userMembers = organizationService.deleteOrgUsers(condition.getIds());
        LoggerHelper.logInfo("小组‘{}’下删除了成员‘{}’", sysOrganization.getOrgName(), new LoggerHelper.PropertyReader<SysUserMember>(userMembers, "userName"));
        return new HashMap<String, String>() {{
            put("orgName", sysOrganization.getOrgName());
        }};
    }

    /**
     * 用户管理的分配部门列表展示
     *
     * @param userId
     * @return
     */
    @RequestMapping("showOrganizations")
    @ResponseBody
    public Object showOrganizations(@RequestParam(value = "userId", required = true) String userId) {
        String str = organizationService.showOrganizations(userId);
        return str;
    }

    /**
     * 点击"我的课题组"
     *
     * @return
     */
    @RequestMapping(value = "myOrganization")
    public String myOrganization() {
//        LoggerHelper.logInfo("查看了课题组列表信息");
        return "hydra_easyui/organization/myOrganization";
    }

    /**
     * 查询我的课题组列表 JSON
     *
     * @param condition 查询条件
     * @param pageSize     每页大小
     * @param pageNumber   当前页起始的数据条数
     * @return
     */
    @RequestMapping(value = "/findMyOrg")
    @ResponseBody
    public Object findMyOrg(
            LoginUser loginUser,
            SearchOrganizationCondition condition,
            @RequestParam(value = "rows", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageNumber) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "id", "asc");
        condition.setAvailable(BaseConstant.INTEGER_TRUE);
        condition.setLikeWords(true);
        Page<SysOrganizationUser> page = organizationService.findMyOrg(loginUser.getId(), condition, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysOrganizationUser.class, "id", "sysUserMember", "sysOrganization", "role")
                .addProperties(SysOrganization.class, "id", "orgName", "orgJobs", "available"));
    }

    /**
     * 我的课题组搜索页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "searchMyOrg")
    @RequiresPermissions(value = "organization:data:list")
    public String searchMyOrg(Model model) {
        return "hydra_easyui/organization/searchMyOrg";
    }

    /**
     * 我的课题组成员管理页面"
     *
     * @param model
     * @return
     */
    @RequestMapping("toMyOrgManage")
    public String toMyOrgManage(
            @RequestParam(value = "id", required = true) String orgId,
            Model model) {
        model.addAttribute("organization", organizationService.findOne(orgId));
        return "hydra_easyui/organization/myOrgManage";
    }

    /**
     * 查询我的课题组成员列表
     *
     * @param searchUserCondition 查询条件
     * @param pageSize            每页大小
     * @param pageNumber          当前页起始的数据条数
     * @return
     */
    @RequestMapping("findMyOrgUser")
    @ResponseBody
    public Object findMyOrgUser(SearchUserCondition searchUserCondition,
                              @RequestParam(value = "rows", defaultValue = "10", required = false) Integer pageSize,
                              @RequestParam(value = "page", defaultValue = "1", required = false) Integer pageNumber) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "sysUserMember.id", "asc");
        searchUserCondition.setAvailable(BaseConstant.INTEGER_TRUE);
        searchUserCondition.setRole(BaseConstant.INTEGER_FALSE);
        Page<SysOrganizationUser> page = organizationService.findMyOrgUser(searchUserCondition, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysOrganizationUser.class, "id", "sysUserMember", "sysOrganization", "role")
//                .addProperties(SysOrganization.class, "id", "orgName")
                .addProperties(SysUserMember.class, "id", "userName", "userNumber", "orgsDescription"));
    }

    /**
     * 到搜索课题组人员页面
     *
     * @param model
     * @return
     */
    @RequestMapping("toSearchMyOrgUser")
    public String searchMyOrgUser(Model model, @RequestParam(value = "orgId", required = true) String orgId) {
        model.addAttribute("org", organizationService.findOne(orgId));
        return "hydra_easyui/organization/searchMyOrgUser";
    }
}
